package com.alison.importbeanregistercondition;

import com.alison.domain.CsvSource;
import com.alison.domain.JdbcSource;
import com.alison.domain.NonSource;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

/**
 * @Author alison
 * @Date 2024/3/27 13:53
 * @Version 1.0
 * @Description
 */

/*
有条件的的注入 对应的source
 */
public class ImportBeanRegistrarConditionImpl implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        importingClassMetadata.getAnnotations();
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableImportBeanRegisterCondition.class.getName()));
        EnableImportBeanRegisterCondition.SourceType sourceType = annotationAttributes.getEnum("sourceType");
        Class<?> beanClass = null;
        String beanName = "";
        switch (sourceType) {
            case CSV:
                beanClass = CsvSource.class;
                beanName = StringUtils.uncapitalize(CsvSource.class.getName());
                break;
            case JDBC:
                beanClass = JdbcSource.class;
                beanName = StringUtils.uncapitalize(JdbcSource.class.getName());
                break;
            default:
                beanClass = NonSource.class;
                beanName = StringUtils.uncapitalize(NonSource.class.getName());
                break;
        }
        RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass);
        registry.registerBeanDefinition(beanName, beanDefinition);
    }
}
